<?php
namespace App\Lib;

class StringHelper{
	
	
    /**
     * 随机6位验证码
     * @param int $length
     * @return string
     */
	public static function  getRandomCode($length=6){
	
		$chars = "123456789abcdefghijklmnopkrstuvwxyz";
		$str = "";
		for($i = 0; $i < $length; $i++){
			$str .= $chars[mt_rand(0, strlen($chars) - 1)];
		}
		return $str;
	}
	
	public static function formatLeftTime($leftTime){
		if ($leftTime <= 0) {
			return "0分钟";
		}

		$day = intval(($leftTime/86400));
		$houre = intval(($leftTime%86400)/3600);
		$minute = intval(($leftTime%86400%3600)/60);

		if ($day > 0) {
			return $day."天".$houre.'小时';
		} elseif ($houre > 0) {
			return $houre.'小时';
		} elseif ($minute > 0) {
			return $minute.'分钟';
		}
        return "0分钟";
	}
	
	public static function fomartTime($time){
		$time = time() - $time;
		$year =  intval(($time/86400)/365);
		$month =  intval(($time/86400)/30);
		$day = intval(($time/86400));
		$houre = intval(($time%86400)/3600);
		$minute = intval($time/60);
		if($year>0){
			return $year."年前";
		}elseif($month>0){
			return $month."月前";
		}elseif($day>0){
			return $day."天前";
		}elseif($houre>0){
			return $houre."小时前";
		}elseif($minute>1){
			return $minute."分钟前";
		}else{
			return "刚刚";
		}
	}
	
	static function PassStart($str,$start,$end=0,$dot="*",$charset="UTF-8"){
		$len = mb_strlen($str,$charset);
		if($start==0||$start>$len){
			$start = 1;
		}
		if($end!=0&&$end>$len){
			$end = $len-2;
		}
		$endStart = $len-$end;
		$top = mb_substr($str, 0,$start,$charset);
		$bottom = "";
		if($endStart>0){
			$bottom =  mb_substr($str, $endStart,$end,$charset);
		}
		$len = $len-mb_strlen($top,$charset);
		$len = $len-mb_strlen($bottom,$charset);
		$newStr = $top;
		for($i=0;$i<$len;$i++){
			if($i > 8){
				continue;
			}
			$newStr.=$dot;
		}
		$newStr.=$bottom;
		return $newStr;
	}
	
	public static function xml_to_json($xmlString){
		$json = simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA);
		$json = json_decode(json_encode($json),true);  
		return $json;
	}
	
}